package com.aichongbang.acb.controller;


import com.aichongbang.acb.po.User;
import com.aichongbang.acb.service.IUserService;
import com.aichongbang.acb.util.JwtUtil;
import com.aichongbang.acb.util.ResultCode;
import com.aichongbang.acb.util.ResultVO;
import com.aichongbang.acb.vo.UserVO;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author acb
 * @since 2021-05-27
 */
@RestController
@RequestMapping("/user")
@Api(tags = "用户相关操作的API")
public class UserController {

    @Resource
    IUserService iUserService;

    //登录
    @PostMapping("/login")
    @ResponseBody
    public ResultVO login(String username, String password, HttpServletResponse response) {
        UserVO userVO = iUserService.login(username, password);
        if (userVO != null && userVO.getTId() > 0) {
            String token = JwtUtil.createJWT(3600000, userVO);
            response.setHeader("Authorization", token);
            return ResultVO.success(userVO);
        } else {
            return ResultVO.fail(ResultCode.USER_LOGIN_ERROR);
        }
    }
    @RequestMapping("/verify")
    @ResponseBody
    public ResultVO verify(HttpServletRequest request){
        String authHeader = request.getHeader("authorization");
        String token = authHeader.substring(7);
        int userId = 0;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (JWTDecodeException j) {
            System.out.println(j.getStackTrace());
        }
        User user = iUserService.getById(userId);
        if(user != null){
            Boolean verify = JwtUtil.isVerify(token, user);
            if(verify){
                return ResultVO.success(user);
            }
            else{
                return ResultVO.fail(ResultCode.USER_AUTHENTICATION_ERROR);
            }
        }
        else{
            return ResultVO.fail(ResultCode.SERVER_EMPTY_RESULT_DATA_ACCESS_ERROR);
        }
    }
    //注册
    @PostMapping("/reg")
    @ResponseBody
    public ResultVO reg(String username,String password,String name,String tel,String email) {
        User user=new User(username,password,name,tel,email);
        if (user != null) {
            Integer integer = iUserService.addUser(user);
//            boolean flag = integer > 0 ? true : false;
            return ResultVO.success(user);
        } else {
            return ResultVO.fail(ResultCode.PARAM_IS_BLANK);
        }
    }
    //获取所有用户信息以及权限
    @GetMapping(value = "/getAllUserPermission")
    @ResponseBody
    public ResultVO getAll(){
        List<UserVO> userVOList = iUserService.getAllUserPermission();
        return ResultVO.success(userVOList);
    }
}
